package com.songlanyun.modules.rabbitmq.mq.consumer;

import cn.hutool.extra.mail.Mail;
import com.rabbitmq.client.Channel;
import com.songlanyun.modules.rabbitmq.MqConstant;
import com.songlanyun.modules.rabbitmq.config.RabbitConfig;
import com.songlanyun.modules.rabbitmq.entity.MsgLog;
 import com.songlanyun.modules.rabbitmq.service.MsgLogService;
import com.songlanyun.modules.rabbitmq.service.MsgLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class SimpleMailConsumer {

   @Autowired
   private MsgLogService msgLogService;


   @RabbitListener(queues = MqConstant.PROCEEDS_QUEUE)
   public void consume(Message message, Channel channel) throws IOException {
     //  Mail mail = MessageHelper.msgToObj(message, Mail.class);
       log.info("收到消息: {}");
      //1--- 取消息id
       String msgId =message.getBody().toString();
       //2---判断消息是否被消费，如果消费则不管
       MsgLog msgLog = msgLogService.selectByMsgId(msgId);
       if (null == msgLog || msgLog.getStatus().equals(MqConstant.MsgLogStatus.CONSUMED_SUCCESS)) {// 消费幂等性
           log.info("重复消费, msgId: {}", msgId);
           return;
       }

       MessageProperties properties = message.getMessageProperties();
       // deliveryTag 用来回传告诉 rabbitmq 这个消息处理成功 清除此消息（basicAck方法）。
       long tag = properties.getDeliveryTag();
       //3-----调用正常的逻辑处理，如果逻辑处理成功 清除此消息
       boolean success = true;
       if (success) {

           msgLogService.updateStatus(msgId, MqConstant.MsgLogStatus.CONSUMED_SUCCESS);

           // if (result()==1)  channel.basicAck(tag, false);
           channel.basicAck(tag, false);// 消费确认 未被ack的消息(unacked)会重新入队并被消费, 这样就保证了消息不会走丢
       } else {
           channel.basicNack(tag, false, true);
       }
       //业务处理结束
   }

}